package com.simon.study.algorithm.collect;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *
 * @author simon
 * @date 2021/12/28 11:21 上午
 */
public class LocalLRUCache<K,V> {
    private int size;
    private int capacity;

    Map<K, Node> map = new HashMap<>();

    private Node head = new Node();
    private Node tail = new Node();

    public class Node{
        Node prev;
        Node next;

        K key;
        V value;

        public Node() { }

        public Node(K key, V value) {
            this.key = key;
            this.value = value;
        }
    }


    public LocalLRUCache(int capacity) {
        this.capacity = capacity;
        this.size = 0;
        head.next = tail;
        tail.prev = head;
    }

    public V get(K key) {
        Node node = map.get(key);
        if (node == null) {
            return null;
        }
        moveToHead(node);
        return node.value;
    }

    public void put(K key, V value) {
        Node node = map.get(key);
        if (node == null) {
            Node newNode = new Node(key, value);
            addToHead(newNode);
            map.put(key, newNode);
            size++;
            if (size > capacity) {
                removeTail();
            }
        } else {
            node.value = value;
            moveToHead(node);
        }
    }

    private void removeTail() {
        Node lastNode = tail.prev;
        map.remove(lastNode.key);
        removeNode(lastNode);
        size--;
    }

    private void moveToHead(Node node) {
        removeNode(node);
        addToHead(node);
    }

    private void removeNode(Node node) {
        node.prev.next = node.next;
        node.next.prev = node.prev;
    }

    private void addToHead(Node node) {
        node.next = head.next;
        head.next.prev = node;
        node.prev = head;
        head.next = node;
    }
}
